import network
import espnow
import time
import random
import get_mpu_data
import _thread
from machine import Pin
from mpu6050 import accel
import machine

sta = network.WLAN(network.STA_IF)    # Enable station mode for ESP
sta.active(True)
sta.disconnect()        # Disconnect from last connected WiFi SSID

e = espnow.ESPNow()     # Enable ESP-NOW
e.active(True)

peer1 = b'\xd8\xbf\xc0\xfa,\xc7'   # MAC address of peer1's wifi interface
e.add_peer(peer1)                     # add peer1 (receiver1)
#如果有多个接收都就在这下面接着增加peer2...

print("Starting...")            # Send to all peers

def main():
    sda=Pin(25)
    scl=Pin(26)
    i2c1=machine.I2C(1,sda=sda,scl=scl,freq=40000)
    cgq=accel(i2c1,0)
    while True:
        v=cgq.get_values()
        acX=v['AcX']/16384.0
        acY=v['AcY']/16384.0
        
#         num_angle=random.randint(65,115)
        direc = 65+(acX+1)*25
        direc=int(direc)
        e.send(peer1, "angle#"+str(direc), True)     # send commands to pear 1
        
#         num_run=random.randint(500,1023)
#         ran_num=random.random()
        if acY<0:
            rand_dir='front'
            run_num=500-acY*500
            run_num=int(run_num)
        else:
            rand_dir='back'
            run_num=500+acY*500
            run_num=int(run_num)
        e.send(peer1, "run#"+rand_dir+"#"+str(run_num), True)     # send commands to pear 1

if __name__ == "__main__":
    main()
